/**
 * 数据请求
 */
import http from '@ohos.net.http';
import { ChatResponse } from '../common/bean/ChatResponse';
import { Constants } from '../common/Constants';
import { Log } from '../common/Log';

class HttpRequest {
  instance: http.HttpRequest;
  buffer: ArrayBuffer = new ArrayBuffer(0)

  constructor() {
    this.instance = http.createHttp();
  }

  post = (appid: string, chatId: string, content: string, callBack: (responseStr: string) => void): void =>  {

    Log.info(Constants.LOG_TAG_NAME, `chat request: ${Constants.CHAT_SERVER_URL}  ${chatId} ${content}`);
    // return new Promise((resolve, reject) => {
      // this.instance.on('headersReceive', (header) => {
      //   console.info('header: ' + JSON.stringify(header))
      // })
      this.instance.on('dataReceive', (data: ArrayBuffer) => {
        const result = arrayBufferToString(data)
        callBack(result)
      })
      // this.instance.on('dataReceiveProgress', (info: http.DataReceiveProgressInfo) => {
      //
      // })
      // this.instance.on('dataEnd', () => {
      //   this.buffer
      //   console.info('dataEnd')
      //
      //   this.buffer
      // })

      this.instance.requestInStream(`${Constants.CHAT_SERVER_URL}`, {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json',
          'Authorization': Constants.CHAT_AUTHORIZATION + appid
        },
        extraData: {
          "chatId": chatId,
          "stream": true,
          "messages": [
            {
              "content": content,
              "role": "user"
            }
          ]
        },
        expectDataType: http.HttpDataType.STRING
      }).then((ret) => {
        this.instance.off('dataReceive')
        Log.info(Constants.LOG_TAG_NAME, `========chatResponsed request: ${JSON.stringify(ret)}`);
        // // Log.info(Constants.LOG_TAG_NAME, `========chatResponsed request: ${JSON.stringify(ret)}`);
        // // Log.info(Constants.LOG_TAG_NAME, `========chatResponsed request: ${JSON.stringify(ret)}`);
        // // Log.info(Constants.LOG_TAG_NAME, `========chatResponsed request: ${JSON.stringify(ret)}`);
        // // Log.info(Constants.LOG_TAG_NAME, `========chatResponsed request: ${JSON.stringify(ret)}`);
        // // Log.info(Constants.LOG_TAG_NAME, `========chatResponsed request: ${JSON.stringify(ret)}`);
        //
        // if (ret.responseCode === http.ResponseCode.OK) {
        //   // Log.info(Constants.LOG_TAG_NAME, `========chatok request: ${JSON.stringify(ret.result)}`);
        //   // Log.info(Constants.LOG_TAG_NAME, `========chatok request: ${JSON.stringify(ret.result)}`);
        //   // Log.info(Constants.LOG_TAG_NAME, `========chatok request: ${JSON.stringify(ret.result)}`);
        //   // Log.info(Constants.LOG_TAG_NAME, `========chatok request: ${JSON.stringify(ret.result)}`);
        //   // Log.info(Constants.LOG_TAG_NAME, `========chatok request: ${JSON.stringify(ret.result)}`);
        //   Log.info(Constants.LOG_TAG_NAME, `========chatok request: ${JSON.stringify(ret.result)}`);
        //
        //
        //   // let result = JSON.parse(ret.result as string);
        //   // let newChatId = result.newChatId;
        //   // let choice = result['choices'][0];
        //   //
        //   // let content = choice['message']['content'];
        //   // resolve(new ChatResponse(newChatId, content));
        // } else {
        //   // let result = JSON.parse(ret.result as string);
        //   // resolve(new ChatResponse("", result.message));
        // }
      }).catch((err) => {
        Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // Log.error(Constants.LOG_TAG_NAME, `===chat faild: ${JSON.stringify(err)}`);
        // reject(new ChatResponse("", "服务器开小差了，请稍后尝试！"));
      })
    // });
  }
}

function concatenateArrayBuffers(buffer1: ArrayBuffer, buffer2: ArrayBuffer): ArrayBuffer {
  const totalLength = buffer1.byteLength + buffer2.byteLength;
  const result = new ArrayBuffer(totalLength);
  const resultView = new Uint8Array(result);

  resultView.set(new Uint8Array(buffer1), 0);
  resultView.set(new Uint8Array(buffer2), buffer1.byteLength);

  return result;
}

function arrayBufferToString(buffer: ArrayBuffer): string {
  // Create a Uint8Array view of the buffer
  const uint8Array = new Uint8Array(buffer);

  // Initialize an empty string to store the result
  let result = '';

  // Decode each byte to a character
  for (let i = 0; i < uint8Array.length; i++) {
    result += String.fromCharCode(uint8Array[i]);
  }

  // Decode the string using decodeURIComponent and escape
  try {
    result = decodeURIComponent(escape(result));
  } catch (e) {
    throw new Error('Invalid UTF-8 data');
  }

  return result;
}

export const HttpUtil2 = new HttpRequest();